import 'dart:convert';
import 'dart:io';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:convert/convert.dart';
import 'package:flutter_aygsh/base/application.dart';
import 'package:flutter_aygsh/util/Toast.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_aygsh/entity/banner_entity.dart';
import 'package:flutter_aygsh/entity/native_entity.dart';
import 'package:flutter_aygsh/util/GridPage.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../liz_home/goods/BrandDetail.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:url_launcher/url_launcher.dart';
import '../base/Constant.dart';
import '../http/Api.dart';
import '../http/HttpUtil.dart';
import '../util/SignUtil.dart';
import '../entity/goods_list_entity.dart';
import '../liz_home/search/SearchGoods.dart';
import '../util/AppSaveInfoUtil.dart';
// import './goods/shop_detail_page.dart';
import './goods/GoodsDetail.dart';
import '../liz_mine/set/InformNews.dart';
import '../liz_home/qianggou/QiangGou.dart';
import '../liz_home/goods/ShopGoodsList.dart';
import '../shopper/BecomeShopper.dart';
import '../base/WebPage.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import '../liz_home/phb/phb.dart';
import '../liz_home/pinpai/pinpai.dart';
import '../liz_mine/set/InviteFriend.dart';
import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';
import '../main.dart';

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return HomeFragmentState();
  }
}

class HomeFragmentState extends State<HomePage>
    with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  List<NativeData> datas = new List();
  List<Widget> list = List();
  List<GoodsModelData> shopData = [];
  List<BannerModelData> bannerData = [];
  List<BannerModelData> bannerData2 = [];
  List<BannerModelData> bannerData3 = [];
  List<BannerModelData> bannerData4 = [];
  bool autoplay = false;
  int page = 1;
  Color currentColor = mainColor;
  EasyRefreshController _controller = EasyRefreshController();

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return new Scaffold(
      appBar: PreferredSize(
          child: AppBar(
            elevation: 0.0,
            backgroundColor: currentColor,
          ),
          preferredSize: Size.fromHeight(0)),
      body: Container(
        color: Colors.white,
        child: Stack(
          children: <Widget>[
            // 裁切的控件
            ClipPath(
                // 只裁切底部的方法
                clipper: BottonClipper(),
                child: Container(
                  color: currentColor,
                  height: ScreenUtil.getInstance().setWidth(DP_200) * 2,
                )),
            new NotificationListener(
              onNotification: (ScrollNotification note) {
                if (note is ScrollUpdateNotification && note.depth == 0) {}
                return false;
              },
              child: new EasyRefresh(
                enableControlFinishRefresh: true,
                enableControlFinishLoad: true,
                taskIndependence: true,
                controller: _controller,
                header: MaterialHeader(),
                footer: MaterialFooter(),
                child: CustomScrollView(shrinkWrap: true, slivers: <Widget>[
                  SliverToBoxAdapter(
                    child: Container(
                        child: Column(
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.fromLTRB(
                              ScreenUtil.getInstance().setWidth(DP_40),
                              ScreenUtil.getInstance().setHeight(DP_50),
                              ScreenUtil.getInstance().setWidth(DP_40),
                              0),
                          height: 70,
                          child: Row(
                            // icon_zhi_1 icon_zheng  icon_hui  icon_shou
                            children: <Widget>[
                              Expanded(
                                  flex: 1,
                                  child: Row(
                                    children: <Widget>[
                                      Image.asset("images/icon_zhi_1.png"),
                                      Container(
                                        width: ScreenUtil.getInstance()
                                            .setWidth(DP_10),
                                        height: 1,
                                      ),
                                      Text(
                                        '严选正品',
                                        style: TextStyle(
                                            color: Colors.white,
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(SMALL_FONT_SIZE)),
                                      )
                                    ],
                                  )),
                              Expanded(
                                  flex: 1,
                                  child: Row(
                                    children: <Widget>[
                                      Image.asset("images/icon_zheng.png"),
                                      Container(
                                        width: ScreenUtil.getInstance()
                                            .setWidth(DP_10),
                                        height: 1,
                                      ),
                                      Text('全球直采',
                                          style: TextStyle(
                                              color: Colors.white,
                                              fontSize: ScreenUtil.getInstance()
                                                  .setSp(SMALL_FONT_SIZE)))
                                    ],
                                  )),
                              Expanded(
                                  flex: 1,
                                  child: Row(
                                    children: <Widget>[
                                      Image.asset("images/icon_hui.png"),
                                      Container(
                                        width: ScreenUtil.getInstance()
                                            .setWidth(DP_10),
                                        height: 1,
                                      ),
                                      Text('假一赔十',
                                          style: TextStyle(
                                              color: Colors.white,
                                              fontSize: ScreenUtil.getInstance()
                                                  .setSp(SMALL_FONT_SIZE)))
                                    ],
                                  )),
                              Expanded(
                                  flex: 1,
                                  child: Row(
                                    children: <Widget>[
                                      Image.asset("images/icon_shou.png"),
                                      Container(
                                        width: ScreenUtil.getInstance()
                                            .setWidth(DP_10),
                                        height: 1,
                                      ),
                                      Text('售后无忧',
                                          style: TextStyle(
                                              color: Colors.white,
                                              fontSize: ScreenUtil.getInstance()
                                                  .setSp(SMALL_FONT_SIZE)))
                                    ],
                                  )),
                            ],
                          ),
                        ),
                        initTop(),
                        initMK()
                      ],
                    )),
                  ),
                  SliverList(
                    delegate: SliverChildBuilderDelegate(
                      (context, index) {
                        if (bannerData3.length > 0) {
                          return banner3(context, index);
                        } else {
                          return Visibility(
                            visible: true,
                            child: Container(width: 0, height: 0),
                          );
                        }
                      },
                      childCount: bannerData3.length,
                    ),
                  ),
                  SliverToBoxAdapter(
                      child: Container(
                          color: white,
                          child: Column(
                            children: <Widget>[
                              Container(
                                  //广告位
                                  padding: EdgeInsets.fromLTRB(
                                      ScreenUtil.getInstance().setWidth(DP_30),
                                      0,
                                      ScreenUtil.getInstance().setWidth(DP_30),
                                      0),
                                  margin: EdgeInsets.fromLTRB(
                                      0,
                                      ScreenUtil.getInstance().setHeight(DP_30),
                                      0,
                                      0),
                                  height:
                                      (ScreenUtil.getInstance().setWidth(750) *
                                          0.28),
                                  child: Swiper(
                                    itemBuilder:
                                        (BuildContext context, int index) {
                                      return new ClipRRect(
                                        child: bannerData2[index].img == null ||
                                                bannerData2[index].img == ''
                                            ? Image.asset(
                                                'images/pic_default.png')
                                            : CachedNetworkImage(
                                                fit: BoxFit.fill,
                                                imageUrl: Api.BaseUrl +
                                                    'public/upload/' +
                                                    bannerData2[index]
                                                        .img
                                                        .replaceAll('\\', '/'),
                                                placeholder: (context, url) =>
                                                    Image.asset(
                                                        'images/pic_default.png'),
                                                errorWidget: (context, url,
                                                        error) =>
                                                    Image.asset(
                                                        'images/pic_default.png'),
                                              ),
                                        borderRadius:
                                            BorderRadius.circular(10.0),
                                      );
                                    },
                                    itemCount: bannerData2 == null
                                        ? 0
                                        : bannerData2.length,
                                    pagination: new SwiperPagination(
                                        builder: DotSwiperPaginationBuilder(
                                            color: Colors.grey,
                                            activeColor: Colors.blue,
                                            size: 7.0,
                                            activeSize: 7.0)),
                                    scrollDirection: Axis.horizontal,
                                    autoplay:
                                        bannerData2.length > 1 ? true : false,
                                    onIndexChanged: (index) {},
                                    onTap: (index) {
                                      if (bannerData2[index].type == '1') {
                                        if (bannerData2[index].href != "") {}
                                      } else if (bannerData2[index].type ==
                                          '2') {
                                        if (bannerData2[index].type_value !=
                                            "") {
                                          Navigator.of(context).push(
                                              new MaterialPageRoute(
                                                  builder: (context) {
                                            return GoodsDetailPage(
                                              goods_id:
                                                  bannerData2[index].type_value,
                                            );
                                          }));
                                        }
                                      }
                                    },
                                  )),
                              Container(
                                  //猜你喜欢
                                  margin: EdgeInsets.fromLTRB(
                                    ScreenUtil.getInstance().setWidth(DP_30),
                                    ScreenUtil.getInstance().setHeight(DP_30),
                                    ScreenUtil.getInstance().setWidth(DP_30),
                                    ScreenUtil.getInstance().setHeight(DP_30),
                                  ),
                                  height:
                                      ScreenUtil.getInstance().setHeight(DP_70),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.only(
                                        topLeft: Radius.circular(10),
                                        topRight: Radius.circular(10)),
                                    image: DecorationImage(
                                        image: AssetImage(
                                            "images/cainixihuan.png"),
                                        fit: BoxFit.fitHeight),
                                  )),
                              Container(
                                color: f0Color,
                              ),
                            ],
                          ))),
                  SliverGrid(
                    gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                      maxCrossAxisExtent: MediaQuery.of(context).size.width / 2,
                      mainAxisSpacing: 0.0,
                      crossAxisSpacing: 0,
                      childAspectRatio: 0.625, //子控件宽高比
                    ),
                    delegate: SliverChildBuilderDelegate(
                      (BuildContext context, int index) {
                        return shopData.length > 0
                            ? Container(
                                child: getItemContainer(context, index),
                                color: f0Color,
                                padding: EdgeInsets.fromLTRB(
                                    index % 2 == 0 ? 10 : 5,
                                    10,
                                    index % 2 == 1 ? 10 : 5,
                                    0),
                              )
                            : Container();
                      },
                      childCount: shopData.length % 2 == 0
                          ? shopData.length
                          : shopData.length + 1,
                    ),
                  ),
                ]),
                onRefresh: () async {
                  page = 1;
                  loadGoods();
                  loadBanner();
                },
                onLoad: () async {
                  page++;
                  loadGoods();
                },
              ),
            ),
            Container(
              child: Row(
                children: <Widget>[
                  Padding(
                      padding: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setWidth(DP_30), 0, 0, 0),
                      child: GestureDetector(
                          onTap: () {
                            Navigator.of(context)
                                .push(new MaterialPageRoute(builder: (context) {
                              return new InformNewsPage();
                            }));
                          },
                          child: Row(
                            children: <Widget>[
                              Image.asset("images/home_xiaoxi.png"),
                            ],
                          ))),
                  Expanded(
                    child: Container(
                      height: ScreenUtil.getInstance().setHeight(DP_80),
                      child: Center(
                        child: new GestureDetector(
                          child: Container(
                            padding: EdgeInsets.fromLTRB(
                                ScreenUtil.getInstance().setHeight(DP_20),
                                ScreenUtil.getInstance().setWidth(DP_10),
                                ScreenUtil.getInstance().setHeight(DP_20),
                                ScreenUtil.getInstance().setWidth(DP_10)),
                            margin: EdgeInsets.fromLTRB(
                                ScreenUtil.getInstance().setHeight(DP_20),
                                0,
                                ScreenUtil.getInstance().setHeight(DP_20),
                                0),
                            decoration: BoxDecoration(
                                color: Color.fromARGB(120, 255, 255, 255),
                                borderRadius: BorderRadius.circular(DP_40)),
                            child: new Row(
                              children: <Widget>[
                                Icon(
                                  Icons.search,
                                  size: 25,
                                  color: Colors.white,
                                ),
                                Text(
                                  '搜索商品、品牌',
                                  style: TextStyle(
                                      color: Colors.white, fontSize: 14),
                                )
                              ],
                            ),
                          ),
                          onTap: () {
                            Navigator.of(context)
                                .push(new MaterialPageRoute(builder: (context) {
                              return new SearchGoodsPage();
                            }));
                          },
                        ),
                      ),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {},
                    child: Padding(
                      padding: EdgeInsets.fromLTRB(
                          0, 0, ScreenUtil.getInstance().setWidth(DP_30), 0),
                      child: Row(
                        children: <Widget>[
                          GestureDetector(
                            onTap: () {
                              getString(TOKEN).then((value) {
                                if (value == null) {
                                  Navigator.of(context).pushNamed('login');
                                } else {
                                  Navigator.of(context).push(
                                      new MaterialPageRoute(builder: (context) {
                                    return new InviteFriendPage();
                                  }));
                                }
                              });
                            },
                            child: Image.asset("images/home_share.png"),
                          )
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              decoration: BoxDecoration(color: currentColor),
            ),
          ],
        ),
      ),
    );
  }

  Widget banner3(BuildContext context, int index) {
    //品牌活动
    return GestureDetector(
        onTap: () {
          print(bannerData3[index].type_value);
          print(bannerData3[index].type);

          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return new BrandDetailPage(
              brand_id: bannerData3[index].type_value.toString(),
            );
          }));

          // if (bannerData3[index].href != null) {
          //   Navigator.of(context)
          //       .push(new MaterialPageRoute(builder: (context) {
          //     return new WebPage(url: bannerData3[index].href);
          //   }));
          // }
        },
        child: Container(
          child: bannerData3[index].img == null || bannerData3[index].img == ''
              ? Image.asset('images/pic_default.png')
              : CachedNetworkImage(
                  width: ScreenUtil.getInstance().setWidth(750),
                  height: ScreenUtil.getInstance().setWidth(750) * 0.38,
                  fit: BoxFit.fill,
                  imageUrl: Api.BaseUrl +
                      'public/upload/' +
                      bannerData3[index].img.replaceAll('\\', '/'),
                  placeholder: (context, url) => Image.asset(
                    'images/pic_default.png',
                    width: ScreenUtil.getInstance().setWidth(750),
                    height: ScreenUtil.getInstance().setWidth(750) * 0.38,
                  ),
                  errorWidget: (context, url, error) => Image.asset(
                    'images/pic_default.png',
                    width: ScreenUtil.getInstance().setWidth(750),
                    height: ScreenUtil.getInstance().setWidth(750) * 0.38,
                  ),
                ),
        ));
  }

  loadFirstService() async {
    //首页模块
    try {
      Map map = new Map.from({
        "sign_type": createSignType(Api.URL_DIY_MODULE),
      });
      Response<String> response =
          await HttpUtil().post(Api.URL_DIY_MODULE, data: getSign(map));
      Map userMap = json.decode(response.toString());
      // print(userMap);
      var naviEntity = NativeEntity.fromJson(userMap);
      if (userMap['code'] == 1 && mounted) {
        // print(naviEntity.data);
        setState(() {
          datas.clear();
          datas.addAll(naviEntity.data);
          list.clear();
          for (int i = 0; i < datas.length; i++) {
            list.add(
              GestureDetector(
                child: new Column(
                  children: <Widget>[
                    (datas[i].icon == '' || datas[i].icon == null)
                        ? Image.asset('images/pic_default.png',
                            width: ScreenUtil.getInstance().setWidth(DP_90),
                            height: ScreenUtil.getInstance().setWidth(DP_90))
                        : CachedNetworkImage(
                            width: ScreenUtil.getInstance().setWidth(DP_90),
                            height: ScreenUtil.getInstance().setWidth(DP_90),
                            fit: BoxFit.cover,
                            imageUrl:
                                Api.BaseUrl + 'public/upload/' + datas[i].icon,
                            placeholder: (context, url) => Image.asset(
                                'images/pic_default.png',
                                width: ScreenUtil.getInstance().setWidth(DP_90),
                                height:
                                    ScreenUtil.getInstance().setWidth(DP_90)),
                            errorWidget: (context, url, error) => Image.asset(
                                'images/pic_default.png',
                                width: ScreenUtil.getInstance().setWidth(DP_90),
                                height:
                                    ScreenUtil.getInstance().setWidth(DP_90))),
                    Padding(
                      padding: EdgeInsets.all(5),
                      child: Text(
                        datas[i].name,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                            fontSize:
                                ScreenUtil.getInstance().setSp(MINI_FONT_SIZE+2),
                            color: Color.fromARGB(255, 66, 66, 66)),
                      ),
                    )
                  ],
                ),
                onTap: () {
                  if (int.parse(datas[i].id) >= 21 &&
                      int.parse(datas[i].id) <= 29) {
                    Navigator.of(context)
                        .push(new MaterialPageRoute(builder: (context) {
                      return new ShopGoodsListPage(
                        cat_id: datas[i].cat_id,
                        name: datas[i].name,
                      );
                    }));
                  }
                  if (int.parse(datas[i].id) == 30) {
                    if (APPLIC.userInfoMap == null) {
                      Navigator.of(context).pushNamed('login');
                      Fluttertoast.showToast(msg: "请先登录");
                      return;
                    }
                    if (APPLIC.userInfoMap['user_msg']['group_id'] == 2||APPLIC.userInfoMap['user_msg']['group_id'] == 1) {
                      Navigator.of(context)
                          .push(new MaterialPageRoute(builder: (context) {
                        return new BecomeShopperPage();
                      }));
                    } else {
                       Fluttertoast.showToast(msg: "已经是最高了");
                      // Navigator.of(context)
                      //     .push(new MaterialPageRoute(builder: (context) {
                      //   return new ShopGoodsListPage(
                      //     cat_id: datas[i].cat_id,
                      //     name: datas[i].name,
                      //   );
                      // }));
                    }
                  }
                },
              ),
            );
          }
        });
      }
    } catch (e) {
      print(e);
    }
  }

  initTop() {
    //轮播图
    return Container(
        // color: grey,
        padding: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setHeight(DP_30),
            0, ScreenUtil.getInstance().setHeight(DP_30), 0),
        margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
        height: (MediaQuery.of(context).size.width -
                ScreenUtil.getInstance().setHeight(DP_60)) /
            2.4,
        child: Swiper(
          itemBuilder: (BuildContext context, int index) {
            return new ClipRRect(
              child:
                  bannerData[index].img == null || bannerData[index].img == ''
                      ? Image.asset(
                          'images/pic_default.png',
                          width: ScreenUtil.getInstance().setWidth(700),
                          height: ScreenUtil.getInstance().setWidth(DP_90),
                          fit: BoxFit.cover,
                        )
                      : CachedNetworkImage(
                          width: ScreenUtil.getInstance().setWidth(700),
                          height: ScreenUtil.getInstance().setWidth(DP_90),
                          fit: BoxFit.cover,
                          imageUrl: Api.BaseUrl +
                              'public/upload/' +
                              bannerData[index].img.replaceAll('\\', '/'),
                          placeholder: (context, url) => Image.asset(
                            'images/pic_default.png',
                            fit: BoxFit.cover,
                            width: ScreenUtil.getInstance().setWidth(700),
                            height: ScreenUtil.getInstance().setWidth(DP_90),
                          ),
                          errorWidget: (context, url, error) => Image.asset(
                            'images/pic_default.png',
                            fit: BoxFit.cover,
                            width: ScreenUtil.getInstance().setWidth(700),
                            height: ScreenUtil.getInstance().setWidth(DP_90),
                          ),
                        ),
              borderRadius: BorderRadius.circular(10.0),
            );
          },
          itemCount: bannerData == null ? 0 : bannerData.length,
          pagination: new SwiperPagination(
              builder: DotSwiperPaginationBuilder(
                  color: Colors.grey,
                  activeColor: Colors.blue,
                  size: 7.0,
                  activeSize: 7.0)),
          scrollDirection: Axis.horizontal,
          autoplay: autoplay,
          onIndexChanged: (index) {
            setState(() {
              if (bannerData != null && bannerData.length > 0)
                currentColor = hexToColor(bannerData[index].color);
            });
          },
          onTap: (index) {
            if (bannerData[index].type == '1') {
              if (bannerData[index].href != "") {}
            } else if (bannerData[index].type == '2') {
              if (bannerData[index].type_value != "") {
                Navigator.of(context)
                    .push(new MaterialPageRoute(builder: (context) {
                  return GoodsDetailPage(
                    goods_id: bannerData[index].type_value,
                  );
                }));
              }
            }
          },
        ));
  }

  initMK() {
    return Container(
      color: divideColor,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            color: Colors.white,
            height: ScreenUtil.getInstance().setHeight(DP_330),
            margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
            padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_10)),
            child: list.length <= 0
                ? Text('')
                : new GridPage(
                    children: list,
                    column: 5,
                    row: 2,
                  ),
          ),
          Container(
            margin: EdgeInsets.fromLTRB(
              ScreenUtil.getInstance().setHeight(DP_20),
              ScreenUtil.getInstance().setHeight(DP_30),
              ScreenUtil.getInstance().setHeight(DP_20),
              ScreenUtil.getInstance().setHeight(DP_20),
            ),
            child: Row(
              children: <Widget>[
                GestureDetector(
                  child: Image.asset("images/card_frist.png",
                      fit: BoxFit.cover,
                      height: ScreenUtil.getInstance().setWidth(750) / 2 -
                          ScreenUtil.getInstance().setHeight(DP_30)),
                  onTap: () {
                    Navigator.of(context)
                        .push(new MaterialPageRoute(builder: (context) {
                      return QiangGouPage();
                    }));
                  },
                ),
                Container(
                  width: ScreenUtil.getInstance().setHeight(DP_10),
                ),
                Expanded(
                  child: Container(
                    child: Column(
                      children: <Widget>[
                        GestureDetector(
                          child: Image.asset("images/card_second.png",
                              fit: BoxFit.cover,
                              height:
                                  (ScreenUtil.getInstance().setWidth(750) / 2 -
                                          ScreenUtil.getInstance()
                                              .setHeight(DP_50)) /
                                      2),
                          onTap: () {
                            Navigator.of(context)
                                .push(new MaterialPageRoute(builder: (context) {
                              return PHBPage();
                            }));
                          },
                        ),
                        Container(
                          height: ScreenUtil.getInstance().setHeight(DP_20),
                        ),
                        GestureDetector(
                          child: Image.asset("images/card_third.png",
                              fit: BoxFit.cover,
                              height:
                                  (ScreenUtil.getInstance().setWidth(750) / 2 -
                                          ScreenUtil.getInstance()
                                              .setHeight(DP_50)) /
                                      2),
                          onTap: () {
                            Navigator.of(context)
                                .push(new MaterialPageRoute(builder: (context) {
                              return PINPAIPage();
                            }));
                          },
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.fromLTRB(
              ScreenUtil.getInstance().setHeight(DP_20),
              0,
              ScreenUtil.getInstance().setHeight(DP_20),
              0,
            ),
            height: ScreenUtil.getInstance().setHeight(DP_90),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(10), topRight: Radius.circular(10)),
              image: DecorationImage(
                  image: AssetImage("images/zhidemai_bg.png"),
                  fit: BoxFit.fitHeight),
            ),
            child: Row(
              children: <Widget>[
                Container(
                  width: ScreenUtil.getInstance().setHeight(20),
                ),
                Image.asset("images/icon_zhi.png"),
                Container(
                  width: ScreenUtil.getInstance().setHeight(10),
                ),
                Text(
                  '优选好价',
                  style: TextStyle(
                      color: Colors.white,
                      fontSize:
                          ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                      fontWeight: FontWeight.w600),
                ),
                Container(
                  width: ScreenUtil.getInstance().setHeight(15),
                ),
                Container(
                  color: Colors.white,
                  height: ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                  width: 1,
                ),
                Container(
                  width: ScreenUtil.getInstance().setHeight(15),
                ),
                Text(
                  '今天值得买',
                  style: TextStyle(
                      color: Colors.white,
                      fontSize:
                          ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE)),
                ),
              ],
            ),
          ),
          //
          Container(
            //横向滑动列表
            color: Colors.white,
            margin: EdgeInsets.fromLTRB(
              ScreenUtil.getInstance().setWidth(DP_20),
              0,
              ScreenUtil.getInstance().setWidth(DP_20),
              0,
            ),
            height: (ScreenUtil.getInstance().setWidth(750) -
                        ScreenUtil.getInstance().setWidth(DP_40)) /
                    4 +
                50,
            child: ListView(
              //设置水平方向排列
              scrollDirection: Axis.horizontal,
              //添加子元素
              children: <Widget>[zdGrid()],
            ),
          ),
          Container(
            height: 5,
            width: ScreenUtil.getInstance().setWidth(750),
            color: f0Color,
          ),
        ],
      ),
    );
  }

  Widget zdGrid() {
    //值得买
    List<Widget> tiles = []; //先建一个数组用于存放循环生成的widget
    Widget content; //单独一个widget组件，用于返回需要���成的内容widget
    for (var item in shopData) {
      tiles.add(GestureDetector(
          onTap: () {
            GoodsModelData model = item;
            Navigator.of(context)
                .push(new MaterialPageRoute(builder: (context) {
              return GoodsDetailPage(
                goods_id: model.goods_id.toString(),
                img: model.img,
              );
            }));
          },
          child: Container(
              width: (ScreenUtil.getInstance().setWidth(750) -
                      ScreenUtil.getInstance().setWidth(DP_40)) /
                  4,
              // color: f0Color,
              child: Column(
                children: <Widget>[
                  item.img == '' || item.img == null
                      ? Image.asset(
                          'images/pic_default.png',
                          width: (ScreenUtil.getInstance().setWidth(750) -
                                  ScreenUtil.getInstance().setWidth(DP_40)) /
                              4,
                          height: (ScreenUtil.getInstance().setWidth(750) -
                                  ScreenUtil.getInstance().setWidth(DP_40)) /
                              4,
                        )
                      : CachedNetworkImage(
                          width: (ScreenUtil.getInstance().setWidth(750) -
                                  ScreenUtil.getInstance().setWidth(DP_40)) /
                              4,
                          height: (ScreenUtil.getInstance().setWidth(750) -
                                  ScreenUtil.getInstance().setWidth(DP_40)) /
                              4,
                          fit: BoxFit.cover,
                          imageUrl: Api.BaseUrl +
                              'public/upload/' +
                              item.img.replaceAll('\\', '/'),
                          placeholder: (context, url) => Image.asset(
                            'images/pic_default.png',
                            width: (ScreenUtil.getInstance().setWidth(750) -
                                    ScreenUtil.getInstance().setWidth(DP_40)) /
                                4,
                            height: (ScreenUtil.getInstance().setWidth(750) -
                                    ScreenUtil.getInstance().setWidth(DP_40)) /
                                4,
                          ),
                          errorWidget: (context, url, error) => Image.asset(
                            'images/pic_default.png',
                            width: (ScreenUtil.getInstance().setWidth(750) -
                                    ScreenUtil.getInstance().setWidth(DP_40)) /
                                4,
                            height: (ScreenUtil.getInstance().setWidth(750) -
                                    ScreenUtil.getInstance().setWidth(DP_40)) /
                                4,
                          ),
                        ),
                  Text(item.goods_name,
                      maxLines: 1,
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance().setSp(26))),
                  Container(
                    margin: EdgeInsets.all(kMargin5),
                    child: RichText(
                      textAlign: TextAlign.left,
                      text: TextSpan(
                          style: TextStyle(color: Colors.red),
                          children: [
                            TextSpan(
                                text: '¥', style: TextStyle(fontSize: 12.0)),
                            TextSpan(
                                text: item.price,
                                style: TextStyle(fontSize: 14.0)),
                            TextSpan(
                              text: item.old_price,
                              style: TextStyle(
                                  fontSize: 11.0,
                                  color: Colors.grey,
                                  decoration: TextDecoration.lineThrough,
                                  decorationColor: Colors.grey),
                            ),
                          ]),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ))));
    }
    content = new Row(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  //商品单个cell
  getItemContainer(BuildContext context, int index) {
    return shopData.length % 2 == 0
        ? new GestureDetector(
            onTap: () {
              //处理点击事件
              GoodsModelData model = shopData[index];
              Navigator.of(context)
                  .push(new MaterialPageRoute(builder: (context) {
                return GoodsDetailPage(
                  goods_id: model.goods_id,
                  img: model.img,
                );
              }));
            },
            child: Container(
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(kMargin10)),
                // color: Colors.white,
                margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
                padding: EdgeInsets.fromLTRB(kMargin10, 0, kMargin10, 0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    shopData[index].img == '' || shopData[index].img == null
                        ? Image.asset(
                            'images/pic_default.png',
                            width: (ScreenUtil.getInstance().setWidth(750) -
                                    kMargin30) /
                                2,
                            height: (ScreenUtil.getInstance().setWidth(750) -
                                    kMargin30) /
                                2,
                          )
                        : CachedNetworkImage(
                            width: (ScreenUtil.getInstance().setWidth(750) -
                                    kMargin30) /
                                2,
                            height: (ScreenUtil.getInstance().setWidth(750) -
                                    kMargin30) /
                                2,
                            fit: BoxFit.fill,
                            imageUrl: Api.BaseUrl +
                                'public/upload/' +
                                shopData[index].img.replaceAll('\\', '/'),
                            placeholder: (context, url) => Image.asset(
                              'images/pic_default.png',
                              width: (ScreenUtil.getInstance().setWidth(750) -
                                      kMargin30) /
                                  2,
                              height: (ScreenUtil.getInstance().setWidth(750) -
                                      kMargin30) /
                                  2,
                            ),
                            errorWidget: (context, url, error) => Image.asset(
                              'images/pic_default.png',
                              width: (ScreenUtil.getInstance().setWidth(750) -
                                      kMargin30) /
                                  2,
                              height: (ScreenUtil.getInstance().setWidth(750) -
                                      kMargin30) /
                                  2,
                            ),
                          ),
                    Container(
                      height: 2,
                    ),
                    Row(
                      children: <Widget>[
                        ClipOval(
                            child: Image.asset(
                          'images/logo.png',
                          width: ScreenUtil.getInstance().setWidth(38),
                          height: ScreenUtil.getInstance().setWidth(38),
                        )),
                        Container(
                            margin: EdgeInsets.only(
                                left: ScreenUtil.getInstance().setWidth(5)),
                            child: Text(
                              '日尚臻选',
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance().setSp(22),
                                  color: Colors.grey),
                            ))
                      ],
                    ),
                    Container(
                      height: 2,
                    ),
                    Text(
                      shopData[index].goods_name,
                      maxLines: 2,
                      style: TextStyle(
                          fontWeight: FontWeight.w600,
                          fontSize: ScreenUtil.getInstance().setSp(26)),
                    ),
                    Container(
                      height: 4,
                    ),
                    shopData[index].lable == '' ||
                            shopData[index].lable == 'null'
                        ? Container()
                        : Container(
                            margin: EdgeInsets.fromLTRB(
                                ScreenUtil.getInstance().setHeight(DP_8),
                                0,
                                ScreenUtil.getInstance().setHeight(DP_8),
                                0),
                            child: GridView.builder(
                              shrinkWrap: true,
                              padding: EdgeInsets.only(top: 0),
                              physics: new NeverScrollableScrollPhysics(),
                              gridDelegate:
                                  SliverGridDelegateWithFixedCrossAxisCount(
                                      crossAxisCount: 4,
                                      mainAxisSpacing: ScreenUtil.getInstance()
                                          .setHeight(DP_10),
                                      crossAxisSpacing: ScreenUtil.getInstance()
                                          .setHeight(DP_10),
                                      childAspectRatio: 2.4),
                              itemBuilder: (BuildContext context, int index1) {
                                List m = shopData[index].lable.split(';');
                                return Container(
                                  decoration: BoxDecoration(
                                      color: Color.fromRGBO(253, 232, 227, 1),
                                      borderRadius: BorderRadius.circular(3)),
                                  alignment: Alignment.center,
                                  padding: EdgeInsets.all(0.8),
                                  child: Text(
                                    m[index1],
                                    style: TextStyle(
                                        color: Colors.red,
                                        fontSize:
                                            ScreenUtil.getInstance().setSp(18)),
                                  ),
                                );
                              },
                              itemCount: shopData[index].lable == null
                                  ? 0
                                  : shopData[index].lable.split(';').length,
                            )),
                    Container(
                      height: 3,
                    ),
                    Container(
                      margin: EdgeInsets.all(kMargin5),
                      child: RichText(
                        textAlign: TextAlign.left,
                        text: TextSpan(
                            style: TextStyle(color: Colors.red),
                            children: [
                              // TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
                              TextSpan(
                                  // text: shopData[index].zk_final_price,
                                  text: MONEY + shopData[index].price,
                                  style: TextStyle(
                                      fontSize:
                                          ScreenUtil.getInstance().setSp(30),
                                      fontWeight: FontWeight.w600)),
                              TextSpan(
                                // text: shopData[index].reserve_price,
                                text: shopData[index].old_price,
                                style: TextStyle(
                                    fontSize: 12.0,
                                    color: Colors.grey,
                                    decoration: TextDecoration.lineThrough,
                                    decorationColor: Colors.grey),
                              ),
                            ]),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                )))
        : (index == shopData.length
            ? Container(
                margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
                color: f0Color,
              )
            : new GestureDetector(
                onTap: () {
                  //处理点击事件
                  GoodsModelData model = shopData[index];
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (context) {
                    return GoodsDetailPage(
                      goods_id: model.goods_id,
                      img: model.img,
                    );
                  }));
                },
                child: Container(
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(kMargin10)),
                    // color: Colors.white,
                    margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
                    padding: EdgeInsets.fromLTRB(kMargin10, 0, kMargin10, 0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        shopData[index].img == '' || shopData[index].img == null
                            ? Image.asset(
                                'images/pic_default.png',
                                width: (ScreenUtil.getInstance().setWidth(750) -
                                        kMargin30) /
                                    2,
                                height:
                                    (ScreenUtil.getInstance().setWidth(750) -
                                            kMargin30) /
                                        2,
                              )
                            : CachedNetworkImage(
                                width: (ScreenUtil.getInstance().setWidth(750) -
                                        kMargin30) /
                                    2,
                                height:
                                    (ScreenUtil.getInstance().setWidth(750) -
                                            kMargin30) /
                                        2,
                                fit: BoxFit.fill,
                                imageUrl: Api.BaseUrl +
                                    'public/upload/' +
                                    shopData[index].img.replaceAll('\\', '/'),
                                placeholder: (context, url) => Image.asset(
                                  'images/pic_default.png',
                                  width:
                                      (ScreenUtil.getInstance().setWidth(750) -
                                              kMargin30) /
                                          2,
                                  height:
                                      (ScreenUtil.getInstance().setWidth(750) -
                                              kMargin30) /
                                          2,
                                ),
                                errorWidget: (context, url, error) =>
                                    Image.asset(
                                  'images/pic_default.png',
                                  width:
                                      (ScreenUtil.getInstance().setWidth(750) -
                                              kMargin30) /
                                          2,
                                  height:
                                      (ScreenUtil.getInstance().setWidth(750) -
                                              kMargin30) /
                                          2,
                                ),
                              ),
                        Container(
                          height: 2,
                        ),
                        Row(
                          children: <Widget>[
                            ClipOval(
                                child: Image.asset(
                              'images/logo.png',
                              width: ScreenUtil.getInstance().setWidth(38),
                              height: ScreenUtil.getInstance().setWidth(38),
                            )),
                            Container(
                                margin: EdgeInsets.only(
                                    left: ScreenUtil.getInstance().setWidth(5)),
                                child: Text(
                                  '日尚臻选',
                                  style: TextStyle(
                                      fontSize:
                                          ScreenUtil.getInstance().setSp(22),
                                      color: Colors.grey),
                                ))
                          ],
                        ),
                        Container(
                          height: 2,
                        ),
                        Text(
                          shopData[index].goods_name,
                          maxLines: 2,
                          style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: ScreenUtil.getInstance().setSp(32)),
                        ),
                        Container(
                          height: 4,
                        ),
                        shopData[index].lable == '' ||
                                shopData[index].lable == 'null'
                            ? Container()
                            : Container(
                                margin: EdgeInsets.fromLTRB(
                                    ScreenUtil.getInstance().setHeight(DP_8),
                                    0,
                                    ScreenUtil.getInstance().setHeight(DP_8),
                                    0),
                                child: GridView.builder(
                                  shrinkWrap: true,
                                  padding: EdgeInsets.only(top: 0),
                                  physics: new NeverScrollableScrollPhysics(),
                                  gridDelegate:
                                      SliverGridDelegateWithFixedCrossAxisCount(
                                          crossAxisCount: 4,
                                          mainAxisSpacing:
                                              ScreenUtil.getInstance()
                                                  .setHeight(DP_10),
                                          crossAxisSpacing:
                                              ScreenUtil.getInstance()
                                                  .setHeight(DP_10),
                                          childAspectRatio: 2.4),
                                  itemBuilder:
                                      (BuildContext context, int index1) {
                                    List m = shopData[index].lable.split(';');
                                    return Container(
                                      decoration: BoxDecoration(
                                          color:
                                              Color.fromRGBO(253, 232, 227, 1),
                                          borderRadius:
                                              BorderRadius.circular(3)),
                                      alignment: Alignment.center,
                                      padding: EdgeInsets.all(0.8),
                                      child: Text(
                                        m[index1],
                                        style: TextStyle(
                                            color: Colors.red,
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(18)),
                                      ),
                                    );
                                  },
                                  itemCount: shopData[index].lable == null
                                      ? 0
                                      : shopData[index].lable.split(';').length,
                                )),
                        Container(
                          height: 3,
                        ),
                        Container(
                          margin: EdgeInsets.all(kMargin5),
                          child: RichText(
                            textAlign: TextAlign.left,
                            text: TextSpan(
                                style: TextStyle(color: Colors.red),
                                children: [
                                  // TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
                                  TextSpan(
                                      // text: shopData[index].zk_final_price,
                                      text: MONEY + shopData[index].price,
                                      style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(30),
                                          fontWeight: FontWeight.w600)),
                                  TextSpan(
                                    // text: shopData[index].reserve_price,
                                    text: shopData[index].old_price,
                                    style: TextStyle(
                                        fontSize: 12.0,
                                        color: Colors.grey,
                                        decoration: TextDecoration.lineThrough,
                                        decorationColor: Colors.grey),
                                  ),
                                ]),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ],
                    ))));
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    loadFirstService();
    loadBanner();
    loadBanner2();
    loadBanner3();
    loadBanner4();
    loadGoods();
    checkVersion();
  }

  checkVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    int versionCode = int.parse(packageInfo.version.replaceAll(".", ""));
    // print('=========当前版本=========');
    // print(versionCode);
    Map map = new Map();
    // map['sign_type'] = SignType.CHECK_VERSION;
    Response<String> response =
        await HttpUtil().post(Api.URL_VERSION, data: {});
    Map userMap = json.decode(response.data);
    print('=========版本检查=========');
    print(userMap);
    if (userMap['code'] == 1 && mounted) {
      if (Platform.isAndroid) {
        //  print('=========是安卓=========');
        // PermissionStatus permission = await PermissionHandler()
        //     .checkPermissionStatus(PermissionGroup.storage);
        var permission = await Permission.storage.status;

        if (permission.isGranted) {
          // print('=========读取权限授权成功=========');
        } else {
          // await PermissionHandler()
          //     .requestPermissions([PermissionGroup.storage]);
          // checkVersion();
          // print('=========读取权限授权失败=========');
          return;
        }
        // print('=========可以版本检查=========');
        int service = int.parse(
            userMap['data']['version_android'].toString().replaceAll(".", ""));
        if (service > versionCode) {
          //做更新处理
          showDialog(
            context: context,
            builder: (context) => new AlertDialog(
              title: new Text('提示'),
              content: new Text('应用发现新的版本，是否下载更新\n' +
                  userMap['data']['update_content_android'].toString()),
              actions: <Widget>[
                new FlatButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: new Text(
                    '取消',
                    style: TextStyle(color: Colors.grey),
                  ),
                ),
                new FlatButton(
                  onPressed: () async {
                    downApk(userMap['data']['down_android']);
                    Navigator.of(context).pop(false);
                  },
                  child: new Text('立即下载', style: TextStyle(color: mainColor)),
                ),
              ],
            ),
          );
        }
      } else {
        int service = int.parse(
            userMap['data']['version_ios'].toString().replaceAll(".", ""));
        if (service > versionCode) {
          //做更新处理
          showDialog(
            context: context,
            builder: (context) => new AlertDialog(
              title: new Text('提示'),
              content: new Text('应用发现新的版本，是否前去下载'),
              actions: <Widget>[
                new FlatButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: new Text(
                    '取消',
                    style: TextStyle(color: Colors.grey),
                  ),
                ),
                new FlatButton(
                  onPressed: () async {
                    final url =
                        "https://itunes.apple.com/cn/app/id1512101126"; // id 后面的数字换成自己的应用 id 就行了
                    if (await canLaunch(url)) {
                      await launch(url, forceSafariVC: false);
                    } else {
                      throw 'Could not launch $url';
                    }
                    Navigator.of(context).pop(false);
                  },
                  child: new Text('立即前往', style: TextStyle(color: mainColor)),
                ),
              ],
            ),
          );
        }
      }
    }
  }

  double percent = 0;
  downApk(String url) async {
    Directory dic;
    dic = await getExternalStorageDirectory();
    Response response;
    File file = File(dic.path +
        "/" +
        DateTime.now().millisecondsSinceEpoch.toString() +
        ".apk");
    if (!file.existsSync()) {
      file.createSync();
    }
    show();
    try {
      response = await new Dio().download(url, file.path,
          onReceiveProgress: (int count, int total) {
        // //进度
        // _showNotification(
        //     (count * 100 / total).toString().substring(0, 5) + '%');
        percent = count * 1.00 / total;
        print(count * 100.00 / total);
        if (total - count <= 10) {
          Navigator.of(context).pop(1);
        }
        mystate(() {});
      });
      if (response.statusCode == 200) {
        _installApk(file.path);
        // flutterLocalNotificationsPlugin.cancelAll();

        // Fluttertoast.showToast(msg: '下载成功');
      }
      // print('downloadFile success---------${response.data}');
    } on DioError catch (e) {
      // Toast.toast(context, msg: '下载出错');
      // print('downloadFile error---------$e');
    }
  }

  var mystate;
  show() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => new StatefulBuilder(
        builder: (context, setState) {
          mystate = setState;
          return new AlertDialog(
            title: Text('下载进度'),
            content: new LinearProgressIndicator(
              value: percent,
              valueColor: new AlwaysStoppedAnimation<Color>(mainColor),
              backgroundColor: Colors.grey,
            ),
          );
        },
      ),
    );
  }

  Future _showNotification(String str) async {
    //安卓的通知配置，必填参数是渠道id, 名称, 和描述, 可选填通知的图标，重要度等等。
    var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
        "1", 'yres', 'yres',
        importance: Importance.Max, priority: Priority.High);
    //IOS的通知配置
    var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
    var platformChannelSpecifics = new NotificationDetails(
        androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
    //显示通知，其中 0 代表通知的 id，用于区分通知。
    await flutterLocalNotificationsPlugin.show(
        0, '更新服务正在运行', '已下载$str', platformChannelSpecifics,
        payload: 'complete');
  }

  // 调用android代码安装apk
  void _installApk(String path) {
    const platform = MethodChannel("com.example.flutter_aygsh/update");
    try {
      // 调用app地址
      platform.invokeMethod(
          'install', {"bundleId": "com.example.flutter_aygsh", "path": path});
    } on PlatformException catch (_) {}
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  Future loadBanner() async {
    //轮播
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_BANNER_LIST),
      "cat_id": "2",
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_BANNER_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    // print(userMap);
    BannerModelEntity bannerEntity = new BannerModelEntity.fromJson(userMap);
    if (userMap['code'] == 1 && mounted) {
      setState(() {
        _controller.finishRefresh();
        bannerData = bannerEntity.data;

        autoplay = true;
      });
    }
  }

  Future loadBanner2() async {
    //广告位
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_BANNER_LIST),
      "cat_id": "8",
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_BANNER_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    // print(userMap);
    BannerModelEntity bannerEntity = new BannerModelEntity.fromJson(userMap);
    if (userMap['code'] == 1 && mounted) {
      setState(() {
        _controller.finishRefresh();
        bannerData2 = bannerEntity.data;
      });
    }
  }

  Future loadBanner3() async {
    //品牌活动
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_BANNER_LIST),
      "cat_id": "6",
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_BANNER_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    // print(userMap);
    BannerModelEntity bannerEntity = new BannerModelEntity.fromJson(userMap);
    if (userMap['code'] == 1 && mounted) {
      setState(() {
        _controller.finishRefresh();
        bannerData3 = bannerEntity.data;
      });
    }
  }

  Future loadBanner4() async {
    //商品活动
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_BANNER_LIST),
      "cat_id": "7",
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_BANNER_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    // print(userMap);
    BannerModelEntity bannerEntity = new BannerModelEntity.fromJson(userMap);
    if (userMap['code'] == 1 && mounted) {
      setState(() {
        _controller.finishRefresh();
        bannerData4 = bannerEntity.data;
      });
    }
  }

  Future loadYX() async {
    //
  }
  Future loadGoods() async {
    //猜你喜欢商品
    Map map = new Map.from({
      'p': page,
      "sign_type": createSignType(Api.URL_GOODS_LIST),
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_GOODS_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    GoodsModelEntity goodsEntity = new GoodsModelEntity.fromJson(userMap);
    print(userMap);
    if (userMap['code'] == 1 && mounted) {
      setState(() {
        if (page == 1) {
          shopData.clear();
          _controller.finishRefresh();
          shopData = goodsEntity.data;
        } else {
          _controller.finishLoad();
          shopData.addAll(goodsEntity.data);
        }
      });
    }
  }
}

class BottonClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    var path = Path();
    path.lineTo(0, 0);
    path.lineTo(0, size.height - 50);
    var firstControlPoint = Offset(size.width / 2, size.height);
    var firstEndPont = Offset(size.width, size.height - 50);
    path.quadraticBezierTo(firstControlPoint.dx, firstControlPoint.dy,
        firstEndPont.dx, firstEndPont.dy);
    path.lineTo(size.width, size.height);
    path.lineTo(size.width, 0);
    return path;
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    return false;
  }
}
